package com.alex.j2se.thread;

import com.google.common.util.concurrent.Runnables;
import lombok.ToString;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Author  : gaojun            <br/>
 * Date    : 2020/3/17                          <br/>
 * Time    : 8:31 下午                         <br/>
 * ---------------------------------------    <br/>
 * Desc    :
 */
public class PoolSizeTest {

    private static ThreadPoolExecutor es = new ThreadPoolExecutor(2,3,5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.DiscardPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            System.out.println("discard..." + r.toString());

        }
    });

    public static void main(String[] args) {
        es.allowCoreThreadTimeOut(true);
        new Thread(() -> {
            for (int i = 0; i < 10; ++i) {
                es.execute(new MyTask(i));
            }
        }).start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            while (true) {
                System.out.println("-poolSize:" + es.getPoolSize());
                System.out.println("queueSize:" + es.getQueue().size());
                System.out.println("activeCount:" + es.getActiveCount());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (es.getPoolSize() == 0 ){
                    break;
                }
            }
        }).start();
    }

    private static class MyTask implements Runnable {

        private int i;

        public MyTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            while (true) {
                System.out.println(i++);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i == 10){
                    break;
                }
            }
        }

        @Override
        public String toString() {
            return "tag_" + i;
        }
    }
}
